package cn.itcast.reggie.controller;

import cn.itcast.reggie.common.R;
import cn.itcast.reggie.dto.SetmealDto;
import cn.itcast.reggie.pojo.Category;
import cn.itcast.reggie.pojo.Setmeal;
import cn.itcast.reggie.service.CategoryService;
import cn.itcast.reggie.service.SetmealDishService;
import cn.itcast.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Transactional
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;


    @PostMapping
    public R add(@RequestBody SetmealDto setmealDto) {
        setmealService.saveDto(setmealDto);
        return R.success("添加套餐成功");
    }

    @GetMapping("/page")
    public R page(int page,int pageSize,String name){
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);

        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        if(StringUtils.isNotEmpty(name)) {
            queryWrapper.like("name",name);
        }

        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc("update_time");
        Page<Setmeal> result = setmealService.page(pageInfo, queryWrapper);

        List<Setmeal> records = result.getRecords();
        List<Setmeal> dtos = new ArrayList<>();
        for (Setmeal setmeal : records) {
            SetmealDto dto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,dto);
            Category category = categoryService.getById(dto.getCategoryId());
            dto.setCategoryName(category.getName());

            dtos.add(dto);
        }
        result.setRecords(dtos);
        return R.success(result);
    }


    @DeleteMapping
    public R delete(String[] ids) {
        categoryService.delete(ids);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R list(Long categoryId,Integer status) {
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        //由于条件必须传递，所有不需要判断是否为null
        queryWrapper.eq("category_id",categoryId);
        queryWrapper.eq("status",status);
        queryWrapper.orderByDesc("update_time");
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }
}    